using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.Material.Craft;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Domain.Inventories;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Material.Craft
{
    /// <summary>
    /// 获取工艺路线列表处理器
    /// </summary>
    public class GetCraftListHandler : IRequestHandler<GetCraftListCommand, ApiPaging<CraftDTO>>
    {
        private readonly IBaseRespository<CraftModel> craftRepository;

        public GetCraftListHandler(IBaseRespository<CraftModel> craftRepository)
        {
            this.craftRepository = craftRepository;
        }

        public Task<ApiPaging<CraftDTO>> Handle(GetCraftListCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<CraftDTO>();

            try
            {
                var crafts = craftRepository.GetAll().Where(x => !x.Isdel);

                // 应用筛选条件
                if (!string.IsNullOrEmpty(request.CraftType))
                {
                    crafts = crafts.Where(x => x.CraftType.Contains(request.CraftType));
                }

                if (!string.IsNullOrEmpty(request.CraftStatus))
                {
                    crafts = crafts.Where(x => x.CraftStatus.Contains(request.CraftStatus));
                }

                var craftList = crafts.Select(x => new CraftDTO
                {
                    Id = x.Id,
                    CraftName = x.CraftName,
                    PreviewImage = x.PreviewImage,
                    PriviewJson=x.PriviewJson,
                    CraftType = x.CraftType,
                    CraftStatus = x.CraftStatus,
                    CraftDesc = x.CraftDesc,
                    CreateName = x.CreateName,
                    CreateTime = x.CreateTime,
                    UpdateName = x.UpdateName,
                    UpdateTime = x.UpdateTime
                }).ToList();

                result.Code = ApiEnum.Success;
                result.Msg = "工艺路线列表获取成功";

                result.TotalCount = craftList.Count();
                result.PageDatas=craftList.OrderByDescending(x => x.Id).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();

            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"获取工艺路线列表失败：{ex.Message}";
            }

            return Task.FromResult(result);
        }
    }
}
